import agreementManager from '@/static/js/Agreement.js';

class DeviceConnectionManager {
    constructor() {
        this.savedDevices = []; // 保存的设备列表（用于快速重连）
        this.currentDevice = null; // 当前连接的设备
        this.deviceCallbacks = {}; // 当前设备的回调
        this.init();
    }

    init() {
        // 从存储加载已保存的设备
        this.loadSavedDevices();
    }

    // 从存储加载设备信息
    loadSavedDevices() {
        try {
            this.savedDevices = uni.getStorageSync('saved_bluetooth_devices') || [];
            console.log('加载已保存设备:', this.savedDevices.length);
        } catch (error) {
            console.error('加载设备失败:', error);
        }
    }

    // 保存设备到存储
    saveDevicesToStorage() {
        uni.setStorageSync('saved_bluetooth_devices', this.savedDevices);
    }

    // 连接设备 - 单设备模式
    async connectDevice(deviceConfig) {
        const { deviceId, protocolName, deviceName } = deviceConfig;

        return new Promise((resolve, reject) => {
            console.log(`开始连接设备: ${deviceId}`);
            
            agreementManager.connectDevice(deviceConfig, {
                onData: (data) => {
                    // 确保数据包含设备ID
                    if (!data.deviceId) {
                        data.deviceId = deviceId;
                    }
                    
                    console.log(`收到设备数据:`, data.Nums);
                    
                    // 数据回调
                    if (this.deviceCallbacks.onData) {
                        this.deviceCallbacks.onData(data);
                    }

                    // 全局数据事件
                    uni.$emit('bluetooth:data-received', data);
                },
                onStatus: (statusDeviceId, status) => {
                    console.log(`设备状态变化: ${status}`);

                    // 更新当前设备状态
                    if (this.currentDevice && this.currentDevice.deviceId === statusDeviceId) {
                        this.currentDevice.connected = status;
                        
                        // 保存到设备列表
                        this.updateSavedDevice(statusDeviceId, status);
                    }

                    // 状态回调
                    if (this.deviceCallbacks.onStatus) {
                        this.deviceCallbacks.onStatus(statusDeviceId, status);
                    }

                    // 全局状态事件
                    uni.$emit('bluetooth:status-changed', {
                        deviceId: statusDeviceId,
                        status
                    });

                    if (!status) {
                        // 设备断开
                        console.log(`设备 ${statusDeviceId} 断开连接`);
                        uni.$emit('bluetooth:device-disconnected', {
                            deviceId: statusDeviceId
                        });
                    }
                }
            }).then(result => {
                // 设置当前设备
                this.currentDevice = {
                    deviceId,
                    deviceName,
                    protocolName,
                    connected: true,
                    config: deviceConfig,
                    connectTime: new Date().getTime()
                };

                // 添加到保存的设备列表（如果不存在）
                this.addToSavedDevices(deviceConfig);
                
                console.log(`设备 ${deviceId} 连接完成`);
                resolve(result);

            }).catch(error => {
                console.error(`设备 ${deviceId} 连接失败:`, error);
                reject(error);
            });
        });
    }

    // 添加到保存的设备列表
    addToSavedDevices(deviceConfig) {
        const exists = this.savedDevices.some(device => 
            device.deviceId === deviceConfig.deviceId
        );
        
        if (!exists) {
            this.savedDevices.push({
                deviceId: deviceConfig.deviceId,
                deviceName: deviceConfig.deviceName,
                protocolName: deviceConfig.protocolName,
                connected: false
            });
            this.saveDevicesToStorage();
        }
    }

    // 更新保存的设备状态
    updateSavedDevice(deviceId, connected) {
        const device = this.savedDevices.find(d => d.deviceId === deviceId);
        if (device) {
            device.connected = connected;
            this.saveDevicesToStorage();
        }
    }

    // 断开设备连接
    disconnectDevice() {
        agreementManager.disconnectDevice();
        
        if (this.currentDevice) {
            this.currentDevice.connected = false;
            this.updateSavedDevice(this.currentDevice.deviceId, false);
            this.currentDevice = null;
        }
    }

    // 重连设备（切换到指定设备）
    async reconnectDevice(deviceConfig) {
        try {
            console.log(`重新连接设备: ${deviceConfig.deviceId}`);
            await this.connectDevice(deviceConfig);
            return true;
        } catch (error) {
            console.error(`重连设备失败:`, error);
            throw error;
        }
    }

    // 扫描设备
    scanDevices(protocolName, onDeviceFound) {
        console.log(`开始扫描 ${protocolName} 设备`);
        return agreementManager.scanDevices(protocolName, onDeviceFound);
    }

    // 停止扫描
    stopScan(protocolName) {
        console.log(`停止扫描 ${protocolName} 设备`);
        agreementManager.stopScan(protocolName);
    }

    // 获取所有已保存设备
    getAllDevices() {
        return this.savedDevices;
    }

    // 获取当前连接设备
    getCurrentDevice() {
        return this.currentDevice;
    }

    // 检查是否有设备连接
    isDeviceConnected() {
        return this.currentDevice ? this.currentDevice.connected : false;
    }

    // 移除设备（从保存列表）
    removeDevice(deviceId) {
        this.savedDevices = this.savedDevices.filter(device => 
            device.deviceId !== deviceId
        );
        
        // 如果移除的是当前设备，断开连接
        if (this.currentDevice && this.currentDevice.deviceId === deviceId) {
            this.disconnectDevice();
        }
        
        this.saveDevicesToStorage();
    }

    // 设置设备数据回调
    setDataCallback(onData) {
        this.deviceCallbacks.onData = onData;
        agreementManager.setDataCallback(onData);
    }

    // 设置设备状态回调
    setStatusCallback(onStatus) {
        this.deviceCallbacks.onStatus = onStatus;
        agreementManager.setStatusCallback(onStatus);
    }

    // 检查连接状态
    async checkConnectionStatus() {
        const currentDevice = agreementManager.getCurrentDevice();
        if (currentDevice && this.currentDevice) {
            const isConnected = agreementManager.isDeviceConnected();
            if (this.currentDevice.connected !== isConnected) {
                this.currentDevice.connected = isConnected;
                this.updateSavedDevice(this.currentDevice.deviceId, isConnected);
                
                // 触发状态变化事件
                uni.$emit('bluetooth:status-changed', {
                    deviceId: this.currentDevice.deviceId,
                    status: isConnected
                });
            }
        }
        
        return this.currentDevice ? this.currentDevice.connected : false;
    }

    // 写入数据到设备
    writeData(data) {
        if (this.isDeviceConnected()) {
            agreementManager.writeData(data);
        }
    }
}

// 创建全局单例
const deviceManager = new DeviceConnectionManager();

export default deviceManager;